package com.netcross.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "PythonOnAndroid";

    SharedPreferences sp;
    private static final int TIME_EXIT=2000;
    private long mBackPressed;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        this.setTitle("登录");
        //进入前先做好python环境的加载
        initPython();
        //如果
        skipLogin();

    }


    // 初始化Python环境
    void initPython() {
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(this));
        }
    }

    //调用python方法 处理webservice请求
    private String callPythonCode(String userName,String loginIp,String loginMac,String password){
        /**
         * 调用 src/main/python/wbc.py 中的 login python方法验证登录
         * @return String   返回值结果可能是 True  Flase  或者 状态码
         *True 表示验证成功 , Flase 验证失败
         */
        Python py = Python.getInstance();
        // 等价用法：py.getModule("hello").get("greet").call("Android");
        PyObject obj = py.getModule("wbc").get("login").call(userName,loginIp,loginMac,password);
        String result = obj.toJava(String.class);
        Log.d(TAG,"accessPassword"+result);
        return  result;
    }

    //记住用户名密码跳过登录
    void skipLogin() {
        /**
         * 当用户记住密码后 从本地文件中取得 getRememberMe  当值为True 跳过登录页面直接进入
         */
        sp = getSharedPreferences("config", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String getRememberMe = sp.getString("rememberMe", "");
        if (getRememberMe.equals("True")) {
            //TODO 需要登录验证 从本地取值向服务器端验证
            Intent intent = new Intent(this, BaseActivity.class);
            this.startActivity(intent);
            finish();
        }
    }

    //获取登录手机的IP地址
    private String getLocalIpAddress() {

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("LOG_TAG", ex.toString());
        }
        return null;
    }

    //点两次退出键后退出程序
    @Override
    public void onBackPressed(){
        if(mBackPressed+TIME_EXIT>System.currentTimeMillis()){
            super.onBackPressed();
            return;
        }else{
            Toast.makeText(this,"再点击一次返回退出程序",Toast.LENGTH_SHORT).show();
            mBackPressed=System.currentTimeMillis();

        }
    }


     public void loginButtonOnCLick(View view) {
        Python py = Python.getInstance();
        String androidId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        EditText userNameEditText = findViewById(R.id.userNameEditTextView);
        String userName = userNameEditText.getText().toString();
        TextView passwordEditText = findViewById(R.id.passwordEditTextText);
        String password = passwordEditText.getText().toString();
        String ip = getLocalIpAddress();
        //判断复选按钮是勾选
         CheckBox rememberMeCheckBox = findViewById(R.id.rememberMeCheckBox);
        if (rememberMeCheckBox.isChecked()) {
            Log.d(TAG, "is check");
            sp = getSharedPreferences("config", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("rememberMe", "True");
            editor.commit();
        }else {
             sp = getSharedPreferences("config", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("rememberMe", "False");
            editor.commit();
        }

        Log.d(TAG,"username: "+userName);
        Log.d(TAG,"password: "+password);
        Log.d(TAG,"ip:  "+ip);
        Log.d(TAG,"androidId: "+androidId);
        String result = "";
        try {
            result = callPythonCode(userName,ip,androidId,password);
            Log.d(TAG,result);
        } catch (Exception e) {
            e.printStackTrace();
            result = "False";
            Log.d(TAG,e.toString());
        }

        Log.d(TAG,result);

        if (result .equals("True")){
             sp = getSharedPreferences("config",MODE_PRIVATE);
             SharedPreferences.Editor  editor = sp.edit();
             editor.putString("userName",userName);
             editor.putString("password",password);
             editor.putString("ip",ip);
             editor.putString( "androidId",androidId);
             editor.commit();
             Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

             //跳转
             Intent intent = new Intent(this,BaseActivity.class);
             this.startActivity(intent);
             finish();
        }
        if(result.equals("False")){
            Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
        }
        if (result.equals("401")){
            Toast.makeText(LoginActivity.this, "用户未激活", Toast.LENGTH_LONG).show();
        }
        if (result.equals("402")){
            Toast.makeText(LoginActivity.this, "用户没有权限", Toast.LENGTH_LONG).show();
        }

    }



}

